package com.niubility.controller;

import com.niubility.entity.Article;
import com.niubility.entity.UsersCollection;
import com.niubility.exception.CustomException;
import com.niubility.server.IArticleServer;
import com.niubility.server.IUsersCollectionServer;
import com.niubility.vo.CollectionLoad;
import com.niubility.vo.GetDate;
import com.niubility.vo.LoadandPage;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName: UsersCollectionController
 * @Description: 与前端交互，实现对收藏表的操作
 * @author: 张家乐
 * @DATE: 2018/1/31
 */
@RestController
@Transactional(rollbackFor = Exception.class)
public class UsersCollectionController {
    @Resource
    IUsersCollectionServer usersCollectionServer;
    @Resource
    IArticleServer<Article> articleServer;
    Logger logger=Logger.getLogger(UsersCollectionController.class);
    /**
     * @Description: 查询当前用户所有收藏
     */
    @RequestMapping("/UserCollectionLoadById")
    public void loadById(HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        String callback="UsersCollection";
        boolean b=false;  //判断传入参数是否正确
        int id=0;

        try {
            callback=request.getParameter("callBack");
            id= Integer.parseInt(request.getSession().getAttribute("userId").toString());
            b=true;
        }catch (Exception e){
            logger.debug("传入参数异常");
        }
        LoadandPage<UsersCollection> loadandPage=new LoadandPage<UsersCollection>();
        String result;
        if(b){
            List<CollectionLoad> collectionLoadList=usersCollectionServer.loadById(id);
            result=callback+"("+ JSONArray.fromObject(collectionLoadList).toString()+")";
        }else{
            result=callback+"("+"{\"state\":"+0+"})";
        }
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            logger.debug("response异常"+e);
        }
    }
    /**
     * @Description: 用户添加收藏
     */
    @RequestMapping("/UserCollectionSave")
    public void save(HttpServletRequest request, HttpServletResponse response) throws CustomException {
        String callback="UsersCollection";
        UsersCollection usersCollection=new UsersCollection();
        int i=0;
        boolean b=false;
        try {
            callback=request.getParameter("callBack");
            usersCollection.setUsersId(Integer.parseInt(request.getSession().getAttribute("userId").toString()));
            usersCollection.setArtId(Integer.parseInt(request.getParameter("artId")));
            usersCollection.setCollDate(GetDate.getDate());
            b=true;
        }catch (Exception e){
            logger.debug("传入参数异常");
        }
        String result = null;
        try {
            if (b){
                 i = usersCollectionServer.save(usersCollection);
                 //int k=10/0;
                 articleServer.UpdateCollectNum(usersCollection.getArtId(), 1);
             }
        }catch (Exception e){
            try {
                response.getWriter().write(callback+"("+"{\"state\":"+0+"})");
            } catch (IOException e1) {
                logger.debug("response异常"+e);
            }
            throw new CustomException();
        }
        result=callback+"("+"{\"state\":"+i+"})";
        try {
            response.getWriter().write(result);
        } catch (IOException ex) {
            logger.debug("response异常"+ex);
        }

    }

    /**
     * @Description: 用户清空收藏
     */
    @RequestMapping("/UserCollectionDeleteAll")
    @ResponseBody
    public void deleteAll(HttpServletRequest request, HttpServletResponse response) throws CustomException {
        String callback="UsersCollection";
        int id=0,i=0;
        boolean b=false;
        try {
            callback=request.getParameter("callBack");
            id=Integer.parseInt(request.getSession().getAttribute("userId").toString());
            b=true;
        }catch (Exception e){
            logger.debug("传入参数错误");
        }
        try{
            if(b){
                i=usersCollectionServer.deleteAll(id);
                List<Integer> list=usersCollectionServer.loadIdsById(id);
                //int k=10/0;
                for (Integer ints:list) {
                    //调用文章收藏数--   通过文章id
                    articleServer.UpdateCollectNum(ints,-1);
                }
            }
        }catch (Exception ex){
            try {
                response.getWriter().write(callback+"("+"{\"state\":"+0+"})");
            } catch (IOException e1) {
                logger.debug("response异常"+ex);
            }
            throw new CustomException();
        }

        String result;
        result=callback+"("+"{\"state\":"+i+"})";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            logger.debug("response异常"+e);
        }
    }
    /**
     * @Description: 用户取消收藏
     */
    @RequestMapping("/UserCollectionDelete")
    @ResponseBody
    public void delete(HttpServletRequest request, HttpServletResponse response) throws CustomException {
        String callback="UsersCollection";
        int i=0;
        UsersCollection usersCollection=new UsersCollection();
        boolean b=false;
        try {
            callback=request.getParameter("callBack");
            usersCollection.setUsersId(Integer.parseInt(request.getSession().getAttribute("userId").toString()));
            usersCollection.setArtId(Integer.parseInt(request.getParameter("artId")));
            b=true;
        }catch (Exception e){
            logger.debug("传入参数错误");
        }
        try{
            if(b){
                i=usersCollectionServer.delete(usersCollection);
                //int k=10/0;
                //调用文章收藏数--  通过文章id
                articleServer.UpdateCollectNum(usersCollection.getArtId(),-1);
            }
        }catch (Exception ex){
            try {
                response.getWriter().write(callback+"("+"{\"state\":"+0+"})");
            } catch (IOException e1) {
                logger.debug("response异常"+e1);
            }
            throw new CustomException();
        }

        String result;
        result=callback+"("+"{\"state\":"+i+"})";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            logger.debug("response异常"+e);
        }
    }

}
